//
//  TicketReservationController.swift
//  AirTravel
//
//  Created by apple on 2021/8/11.
//

import UIKit
import FWPopupView
import Moya
import SwiftyJSON

class TicketReservationController: UIViewController {

    @IBOutlet weak var tabView: UITableView!
    /// 终点站
    @IBOutlet weak var terminalLab: UILabel!
    /// 结束小时
    @IBOutlet weak var end_hoursLab: UILabel!
    /// 结束时间
    @IBOutlet weak var end_dateOfLab: UILabel!
    /// 路程时间
    @IBOutlet weak var journey_timeLab: UILabel!
    /// 车次
    @IBOutlet weak var trainsLab: UILabel!
    /// 出发站
    @IBOutlet weak var start_standingLab: UILabel!
    /// 出发小时
    @IBOutlet weak var start_hoursLab: UILabel!
    /// 出发时间
    @IBOutlet weak var start_dateOfLab: UILabel!
    @IBOutlet weak var timetableBtn: UIButton!
    
    /// 二等座
    @IBOutlet weak var secondClassLab: UILabel!
    
    @IBOutlet weak var priceLab: UILabel!
    /// 提交订单
    @IBOutlet weak var submitOrdersBtn: UIButton!
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    
    var dataStr = ""
    var according = ""
    var difference = "今天"
    /// 出发站名称
    var fromStationName = ""
    /// 到达站名称
    var toStationName = ""
    /// 车次
    var trainNo = ""
    var seatDic : Dictionary<String,Any>?
    var passengersArray = [Dictionary<String,Any>]()
    var dataDic : Dictionary<String,Any>?
    var contactName = ""
    var contactMobile = ""
    var order_id = ""
    var payType = ""
    var maxPrice : Float = 0
    /// 0、12306下单3块一人       1、平台5块一人
    var platformType = 0
    
    
    
    let identifyRS = "RailwaySystemCell"
    let identifyII = "IdentityInformationCell"
    let identifyIE = "IdEditorCell"
    let identifyCC = "ContactCell"
    
    lazy var payView: ChoosePayView = {
        let customPopupView = ChoosePayView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 320))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.white
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "0"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    lazy var snapUpProgressView: SnapUpProgressView = {
        let customPopupView = SnapUpProgressView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 300))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .center
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "0"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    lazy var childBoundAdultView: ChildBoundAdultView = {
        let customPopupView = ChildBoundAdultView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 315))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "1"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    //视图将要显示
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        //设置导航栏背景透明
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(),
                                                                    for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        NotificationCenter.default.addObserver(self, selector: #selector(aliPayClicks), name: Notification.Name("aliPaySucceess"), object: nil)
    }
         
    //视图将要消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //重置导航栏背景
        self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        self.navigationController?.navigationBar.shadowImage = nil
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "车票预定"
        self.timetableBtn.layer.cornerRadius = 11
        self.timetableBtn.layer.borderWidth = 1
        self.timetableBtn.layer.borderColor = UIColor.white.cgColor
        
        self.submitOrdersBtn.layer.cornerRadius = 3
        
        let gradientLayer0 = CAGradientLayer()
        gradientLayer0.cornerRadius = 3
        gradientLayer0.frame = self.submitOrdersBtn.bounds
        gradientLayer0.colors = [
            UIColor(red: 101.0 / 255.0, green: 160.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0).cgColor,
            UIColor(red: 48.0 / 255.0, green: 124.0 / 255.0, blue: 248.0 / 255.0, alpha: 1.0).cgColor]
        gradientLayer0.locations = [0, 1]
        gradientLayer0.startPoint = CGPoint(x: 0, y: 1)
        gradientLayer0.endPoint = CGPoint(x: 1, y: 1)
        self.submitOrdersBtn.layer.addSublayer(gradientLayer0)
        
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.tableFooterView = UIView.init()
        self.tabView.separatorStyle = .none
        self.tabView.register(UINib.init(nibName: "RailwaySystemCell", bundle: nil), forCellReuseIdentifier: identifyRS)
        self.tabView.register(UINib.init(nibName: "IdentityInformationCell", bundle: nil), forCellReuseIdentifier: identifyII)
        self.tabView.register(UINib.init(nibName: "IdEditorCell", bundle: nil), forCellReuseIdentifier: identifyIE)
        self.tabView.register(UINib.init(nibName: "ContactCell", bundle: nil), forCellReuseIdentifier: identifyCC)
        searchTrainsBetweenStations()
    }
    
    @objc func aliPayClicks(notifi : Notification) {
        //订单列表
        let vc = TrainOrderCenterController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //明细
    @IBAction func detailBtn(_ sender: UIButton) {
        let vc = TrainOrderCenterController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //提交订单
    @IBAction func submitOrders(_ sender: UIButton) {
        
        if (self.passengersArray.count == 0) {
            YProgressHUD.showToast("请添加乘客")
            return
        }
        if self.contactName.isEmpty {
            YProgressHUD.showToast("请输入联系人姓名")
            return
        }
        if self.contactMobile.isEmpty {
            YProgressHUD.showToast("请输入联系人电话")
            return
        }
        self.snapUpProgressView.setUpData(dataStr: self.dataStr, fromStationName: self.fromStationName, toStationName: self.toStationName, trainNo: self.trainNo, dataDic: self.dataDic ?? [:], seatDic: self.seatDic ?? [:], passengersArray: self.passengersArray, contactName: self.contactName, contactMobile: self.contactMobile, platformType: self.platformType)
        self.snapUpProgressView.show()
        
    }
    
    //根据城市名称获取城市id接口
    func searchTrainsBetweenStations() {
        cancelableRequest = NetWorkRequest(API1.searchTrainsBetweenStations(parameters: ["departDate":self.dataStr,"fromStationName":self.fromStationName,"toStationName":self.toStationName,"trainNo":self.trainNo]), completion: {[weak self] (responseString) -> (Void) in
            let list = responseString["data"]["list"].arrayObject
            if let array = list {
                let dataDic = array[0] as? Dictionary<String, Any>
                if let dic = dataDic {
                    self?.dataDic = dataDic
                    self?.trainsLab.text = self?.trainNo
                    self?.terminalLab.text = "\(dic["toStationName"] ?? "")"
                    self?.end_hoursLab.text = "\(dic["arriveTime"] ?? "")"
                    self?.start_hoursLab.text = "\(dic["startTime"] ?? "")"
                    let durationMinutes = "\(dic["durationMinutes"] ?? "0")"
                    let dur = Int(durationMinutes)
                    let sfm = self?.secondsToHoursMinutesSeconds(seconds: dur ?? 0)
                    self?.journey_timeLab.text = sfm
                    self?.end_dateOfLab.text = "\(dic["arriveDate"] ?? "")"
                    self?.start_standingLab.text = "\(dic["fromStationName"] ?? "")"
                    self?.start_dateOfLab.text = "\(dic["departDate"] ?? "")"
                    self?.secondClassLab.text = "\(self?.seatDic?["seatName"] ?? "") ￥\(self?.seatDic?["maxPrice"] ?? "")"
                    self?.maxPrice = Float("\(self?.seatDic?["maxPrice"] ?? "0")") ?? 0
                }
            }
            self?.tabView.reloadData()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    //订单支付接口地址
    func orderPay() {
        cancelableRequest = NetWorkRequest(API1.railwaysOrderPay(parameters: ["order_id":self.order_id,"method":"app"]), completion: {[weak self] (responseString) -> (Void) in
            if self?.payType == "4"{
                //调起微信支付
                let req = PayReq.init()
                req.partnerId = "\(responseString["data"]["partnerid"])"
                req.prepayId = "\(responseString["data"]["prepayid"])"
                req.nonceStr = "\(responseString["data"]["noncestr"])"
                req.timeStamp = UInt32("\(responseString["data"]["timestamp"])") ?? 0
                req.package = "\(responseString["data"]["package"])"
                req.sign = "\(responseString["data"]["sign"])"
                WXApi.send(req, completion: nil)
            }else{
                //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
                let appScheme = "AirTravel"
                
                // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
                let orderString = responseString["data"].stringValue
                
                // NOTE: 调用支付结果开始支付
                AlipaySDK.defaultService()?.payOrder(orderString, fromScheme: appScheme, callback: { (resultDic) in
                    
                    print("afafa")
                })
            }
            
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    func secondsToHoursMinutesSeconds(seconds:Int) -> (String) {
        let h = seconds/60
        let m = seconds%60
        if h > 0 {
            if m > 0 {
                return "\(h)时\(m)分"
            }
            return "\(h)时"
        }else{
            if m > 0 {
                return "\(m)分"
            }
            return ""
        }
    }
}

extension TicketReservationController:UITableViewDataSource,UITableViewDelegate{
    
    func numberOfSections(in tableView: UITableView) -> Int{
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            return self.passengersArray.count + 1
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyRS) as! RailwaySystemCell
            cell.selectionStyle = .none
            let username = "\(UserDefaults.standard.value(forKey: "12306Login") ?? "")"
            cell.numberLab.text = username
            return cell
        case 1:
            if indexPath.row == self.passengersArray.count {
                let cell = tableView.dequeueReusableCell(withIdentifier: identifyIE) as! IdEditorCell
                cell.selectionStyle = .none
                cell.addErBtn.addTarget(self, action: #selector(addEr), for: .touchUpInside)
                cell.addCrBtn.addTarget(self, action: #selector(addCr), for: .touchUpInside)
                return cell
            }
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyII) as! IdentityInformationCell
            cell.selectionStyle = .none
            if indexPath.row == 0 {
                ///延迟执行之前的代码
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute:{
                    cell.contentView.addCorner(conrners: [.topLeft,.topRight], radius: 6)
                })
            }
            let dic = self.passengersArray[indexPath.row]
            cell.nameLab.text = "\(dic["name"] ?? "")"
            let identity_type = "\(dic["identity_type"] ?? "")"
            switch identity_type {
            case "1":
                cell.tagLab.text = "成人票"
            case "2":
                cell.tagLab.text = "儿童票"
            case "3":
                cell.tagLab.text = "学生票"
            case "4":
                cell.tagLab.text = "残/军票"
            default:
                cell.tagLab.text = ""
            }
            let doument_type = "\(dic["doument_type"] ?? "")"
            switch doument_type {
            case "1":
                cell.idCardLab.text = "身份证 \(dic["idcard"] ?? "")"
            case "2":
                cell.idCardLab.text = "护照 \(dic["idcard"] ?? "")"
            case "3":
                cell.idCardLab.text = "军人证 \(dic["idcard"] ?? "")"
            case "4":
                cell.idCardLab.text = "回乡证 \(dic["idcard"] ?? "")"
            case "5":
                cell.idCardLab.text = "台胞证 \(dic["idcard"] ?? "")"
            case "6":
                cell.idCardLab.text = "外国人永久居留证 \(dic["idcard"] ?? "")"
            case "99":
                cell.idCardLab.text = "其他 \(dic["idcard"] ?? "")"
            default:
                cell.idCardLab.text = ""
            }
            cell.reductionBtn.addTarget(self, action: #selector(reduction(sender:)), for: .touchUpInside)
            cell.reductionBtn.tag = indexPath.row
            
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyCC) as! ContactCell
            cell.selectionStyle = .none
            cell.nameTf.delegate = self
            cell.phoneTf.delegate = self
            cell.nameTf.text = self.contactName
            cell.phoneTf.text = self.contactMobile
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        switch indexPath.section {
        case 0:
            return 50
        case 1:
            if indexPath.row == self.passengersArray.count {
                return 60
            }
            let dic = self.passengersArray[indexPath.row]
            if dic.count != 0 {
                return 72
            }
            return 0
        default:
            return 137
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        return 8
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        let footView = UIView.init()
        footView.backgroundColor = UIColor.clear
        return footView
    }
    
    @objc func addEr() {
        self.childBoundAdultView.show()
    }
    
    @objc func addCr() {
        let vc = SelectPassengersController()
        vc.identity_type = "1"
        vc.delegate = self
        vc.mutArray = self.passengersArray 
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func reduction(sender:UIButton) {
        self.passengersArray[sender.tag] = [:]
        var i : Float = 0
        for item in self.passengersArray {
            if item.isEmpty == false {
                i += 1
            }
        }
        let price = self.maxPrice * i
        self.priceLab.text = "￥\(price)"
        self.tabView.reloadData()
    }
}

extension TicketReservationController:SnapUpProgressDelegate{
    func snapUpProgressClick(dic: Dictionary<String, Any>) {
        // 4.GCD 主线程/子线程
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.snapUpProgressView.hide()
            self.snapUpProgressView.hideKeyboard()
        }
        
        let key = "\(dic["key"] ?? "")"
        if key == "成功" {
            let order_id = "\(dic["val"] ?? "")"
            self.order_id = order_id
            var i : Float = 0
            for item in self.passengersArray {
                if item.isEmpty == false {
                    i += 1
                }
            }
            let price = self.maxPrice * i
            
            self.payView.setUpData(price: "\(price)")
            self.payView.show()
        }else{
            YProgressHUD.showToast("抢座失败")
        }
        
    }
    
}

extension TicketReservationController:ChildBoundAdultDelegate{//儿童
    func childBoundAdultClick(dic: Dictionary<String, Any>) {
        
    }
}

extension TicketReservationController:SelectPassengersDelegate{
    func selectPassengersClick(array: [Dictionary<String,Any>]) {
        self.passengersArray = array
        var i : Float = 0
        for item in self.passengersArray {
            if item.isEmpty == false {
                i += 1
            }
        }
        
        if self.platformType == 0 {
            let price = self.maxPrice * i + 3 * i
            self.priceLab.text = "￥\(price)"
        }else{
            let price = self.maxPrice * i + 5 * i
            self.priceLab.text = "￥\(price)"
        }
        
        self.tabView.reloadData()
    }
}
extension TicketReservationController:UITextFieldDelegate{
    func textFieldDidEndEditing(_ textField: UITextField){
        if textField.tag == 0 {
            self.contactName = textField.text ?? ""
        }else{
            self.contactMobile = textField.text ?? ""
        }
    }
}

extension TicketReservationController:ChoosePayDelegate{
    func choosePayClick(data: Dictionary<String, Any>) {
        self.payView.hide()
        self.payView.hideKeyboard()
        let key = "\(data["key"] ?? "")"
        self.payType = key
        self.orderPay()
        
//        if key == "1" {//银联
//            self.netWork(goods_id: self.ylID, type: "1")
//        }else if key == "4" {//微信
//            self.netWork(goods_id: self.ylID, type: "4")
//        }
//        else{
//            self.netWork(goods_id: self.ylID, type: "3")
//        }
    }
}
